<template>
  <div class="page-wrapper">
    <el-card class="box-card">
      <div class="header-wrapper">
        <div class="title">巡检任务日历</div>
        <div class="legend">
          <div
            class="legend-item"
            v-for="(item, index) in legendConfig.labelList"
            :key="index"
          >
            <div
              :style="`background-color: ${item.color}`"
              class="signal"
            ></div>
            <span>{{ item.text }}</span>
          </div>
        </div>
        <div style="display:flex;flex-direction:row;align-items:center;">
          <span style="width: 100px;">巡视单位:</span>
          <list-table-new
            ref="klTable"
            v-bind="tableSetting"
            :showTable="false"
            :showSearchLabel="false"
            :showPagination="false"
            :showSearchBtn="false"
            @selectChange="selectChange"
            @defaultSelection="checkedUser"
            @selectAll="selectAll"
          ></list-table-new>
        </div>
        <div class="date-picker-wrapper">
          <span style="margin-right: 10px">查询时间范围:</span>
          <el-date-picker
            v-model="selectedDate"
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            align="right"
            size="small"
          >
          </el-date-picker>
          <el-button
            style="margin-left: 16px"
            type="primary"
            @click="getCalendarList"
            >查询</el-button
          >
        </div>
      </div>
      <div class="calendar-wrapper">
        <el-calendar v-model="value">
          <!-- data -->
          <template v-slot:dateCell="{ date }">
            <div class="calendar-item">
              <div class="calendar-item-date">
                {{ formatDate(date, "month-day") }}
              </div>
              <div v-show="checkIsShowTaskItem(date)">
                <div class="calendar-item-content">
                  <template v-if="findTasksByDay(date)">
                    <div
                      class="task-wrapper"
                      v-for="item in findTasksByDay(date).poList.slice(0, 3)"
                      :key="item.id"
                    >
                      <div
                        :style="`padding:2px;font-size:10px;border-radius:4px;background-color: ${
                          taskStatusToColor[item.status]
                        };`"
                      >
                        {{ formatDate(item.planStartTime, "hour-minute") }}
                      </div>
                      <div class="task-title">{{ item.title }}</div>
                    </div>
                  </template>
                </div>
                <div class="check-more" @click="handleOpenTaskDetail(date)">
                  展开更多
                </div>
              </div>
            </div>
          </template>
        </el-calendar>
      </div>
    </el-card>
    <el-drawer
      :title="formatDate(value)"
      :visible.sync="drawer"
      :direction="direction"
      :before-close="handleClose"
    >
      <el-steps space="64px" direction="vertical">
        <template v-if="findTasksByDay(openDrawerDate)">
          <el-step
            v-for="(item, index) in findTasksByDay(openDrawerDate).poList"
            :key="index"
            :title="item.title"
            :description="item.planStartTime"
            :icon="taskStatusToImage[item.status]"
            @click.native="toPatrolOrderDetail(item)"
          >
          </el-step>
        </template>
      </el-steps>
    </el-drawer>
  </div>
</template>

<script>
import { getPatrolOrderCalendarTasksByDate } from "@/api/orderManagement/patrolOrder.js";
export default {
  data() {
    return {
      value: new Date(),
      legendConfig: {
        labelList: [
          {
            color: "#22bb5f",
            text: "已巡视",
          },
          {
            color: "#fbcb6e",
            text: "巡视中",
          },
          {
            color: "#ff5555",
            text: "不巡视",
          },
          {
            color: "#bababa",
            text: "待巡视",
          },
        ],
      },
      pickerOptions: {},
      selectedDate: [],
      drawer: false,
      direction: "rtl",
      calendarList: [],
      currentDate: {},
      taskStatusToColor: {
        WAIT_PATROL: "#bababa",
        IN_PATROL: "#fbcb6e",
        END_PATROL: "#22bb5f",
        NO_PATROL: "#ff5555",
      },
      taskStatusToImage: {
        WAIT_PATROL: "el-icon-time",
        IN_PATROL: "el-icon-odometer",
        END_PATROL: "el-icon-circle-check",
        NO_PATROL: "el-icon-circle-close",
      },
      // 点击日历表某天展开更多时的日期
      openDrawerDate: "",
      tableSetting: {
        selectionShow: true,
        pageConfig: {
          pageCode: "patrolOrder",
          userId: this.$store.getters.userInfo.namePy,
        },
        searchObj: {
          searchMethod: (params, sortStr) => {
            console.log(params, sortStr)
            this.patrolDeptId = params.patrolDeptId
            // this.getTableData(params, sortStr);
          },
          queryData: {
            page: 1,
            pageSize: 15,
          },
          searchArr: [
            {
              type: "organization",
              label: "巡视单位",
              model: "patrolDeptName",
              idsStr: "patrolDeptId",
            },
          ],
        },
        //过滤器的值
        filterFormData: {},
        //过滤器的默认值
        defaultFilterData: {},
        userCustomData: [],
        column: [
          {
            label: "巡视单位",
            minWidth: "150px",
            prop: "patrolDeptName",
            sortable: "custom",
          }
        ],
        paginationObj: {
          pageSizes: [15, 30, 50, 100],
        },
        totalNumber: 0,
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (row) => {
            this.goDetailPage(row, "patrolOrderDetails", "edit");
          },
        },
      },
      // 巡视单位
      patrolDeptId: ''
    };
  },
  computed: {
    startTime() {
      return (
        this.selectedDate &&
        this.selectedDate.length &&
        this.formatDate(this.selectedDate[0])
      );
    },
    endTime() {
      return (
        this.selectedDate &&
        this.selectedDate.length &&
        this.formatDate(this.selectedDate[1])
      );
    },
    calendarDateList() {
      return this.calendarList.map((item) => item.date);
    },
  },
  methods: {
    selectChange(selected, row) {
      console.log(selected, row)
    },
    checkedUser() {},
    selectAll(selected) {
      console.log(selected)
    },
    // 打开某日详情列表抽屉
    handleOpenTaskDetail(date) {
      this.openDrawerDate = this.formatDate(date);
      this.drawer = true;
    },
    // 关闭抽屉
    handleClose(done) {
      // this.drawer = false
      done();
    },
    // 跳转到巡视工单详情
    toPatrolOrderDetail(data) {
      console.log(data);
      let { href } = this.$router.resolve({
        name: "patrolOrderDetails",
        query: {
          id: data.id,
          pageType: "edit",
        },
      });
      window.open(href, "_blank");
    },
    // 根据查询日期范围获取巡检日历数据
    getCalendarList() {
      this.$refs.klTable && this.$refs.klTable.searchData()
      let params = {
        startTime: this.startTime,
        endTime: this.endTime,
      };
      if(this.patrolDeptId) params.patrolDeptId = this.patrolDeptId
      getPatrolOrderCalendarTasksByDate(params).then((res) => {
        this.calendarList = res.data;
      });
    },
    // 判断是否显示当日巡检任务
    checkIsShowTaskItem(date) {
      const fDate = this.formatDate(date);
      return this.calendarDateList.includes(fDate);
    },
    // 根据当天日期去筛选列表，获取当天的巡检任务列表
    findTasksByDay(day) {
      const date = this.formatDate(day);
      return this.calendarList.find((item) => item.date === date);
    },
    // 获取本月最后一天的日期
    getLastDayDateOfMonth(date) {
      const year = date.getFullYear();
      const month = date.getMonth();
      const lastDay = new Date(year, month + 1, 0).getDate();
      return new Date(year, month, lastDay);
    },
    // 格式化日期（yyyy-MM-dd）
    formatDate(inputDate, type = "full") {
      const date = new Date(inputDate);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, "0");
      const day = date.getDate().toString().padStart(2, "0");
      const hours = date.getHours().toString().padStart(2, "0");
      const minutes = date.getMinutes().toString().padStart(2, "0");
      const seconds = date.getSeconds().toString().padStart(2, "0");

      if (type === "full") return `${year}-${month}-${day}`;
      if (type === "month-day") return `${month}-${day}`;
      if (type === "day") return `${day}`;
      if (type === "hour-minute") return `${hours}:${minutes}`;
    },
  },
  created() {
    const date = new Date();
    const firstStartTime = `${date.getFullYear()}-${date.getMonth() + 1}-01`;
    const firstEndTime = this.getLastDayDateOfMonth(date);
    this.currentDate = {
      year: date.getFullYear(),
      month: date.getMonth() + 1,
    };
    this.selectedDate = [firstStartTime, this.formatDate(firstEndTime)];
    this.getCalendarList();

    // 给日历的`上个月`, `下个月`按钮绑定点击事件
    this.$nextTick(() => {
      let prevBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(1)"
      );
      prevBtn.addEventListener("click", () => {
        if (this.currentDate.month == 1) {
          (this.currentDate.year = this.currentDate.year - 1),
            (this.currentDate.month = 12);
        } else {
          this.currentDate.month = this.currentDate.month - 1;
        }
        const prevstartTime = new Date(
          `${this.currentDate.year}-${this.currentDate.month}-01`
        );
        const prevendTime = this.getLastDayDateOfMonth(new Date(prevstartTime));
        this.selectedDate = [prevstartTime, prevendTime];
        console.log("prev", prevstartTime, "-", prevendTime);
        this.getCalendarList();
      });

      let currentBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(2)"
      );
      currentBtn.addEventListener("click", () => {
        // 重置为当前月份
        this.selectedDate = [firstStartTime, firstEndTime];
        this.currentDate = {
          year: date.getFullYear(),
          month: date.getMonth() + 1,
        };
        this.getCalendarList();
      });

      let nextBtn = document.querySelector(
        ".el-calendar__button-group .el-button-group>button:nth-child(3)"
      );
      nextBtn.addEventListener("click", () => {
        if (this.currentDate.month == 12) {
          (this.currentDate.year = this.currentDate.year + 1),
            (this.currentDate.month = 1);
        } else {
          this.currentDate.month = this.currentDate.month + 1;
        }
        const nextstartTime = new Date(
          `${this.currentDate.year}-${this.currentDate.month}-01`
        );
        const nextendTime = this.getLastDayDateOfMonth(new Date(nextstartTime));
        this.selectedDate = [nextstartTime, nextendTime];
        // console.log("next", nextstartTime, "-", nextendTime);
        this.getCalendarList();
      });
    });
  },
};
</script>

<style lang="less" scoped>
.page-wrapper {
  width: 100%;
  height: 100%;
  border: 1px solid transparent;

  .box-card {
    margin: 20px;

    .header-wrapper {
      display: flex;
      flex-direction: row;
      align-items: center;

      .title {
        width: 200px;
        font-size: 20px;
        text-align: left;
      }

      .legend {
        font-size: 14px;
        display: flex;
        justify-content: center;
        flex: 1;
        flex-direction: row;

        .legend-item {
          margin: 0 10px;
          .signal {
            margin-right: 10px;
            display: inline-block;
            width: 10px;
            height: 10px;
          }
        }
      }

      .calendar-wrapper {
        width: 100%;
      }
    }
  }
}

.task-wrapper {
  display: flex;
  flex-direction: row;
  align-items: center;
  .task-title {
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏溢出内容 */
    text-overflow: ellipsis;
    margin: 2px 0 2px 6px;
  }
}

/deep/.el-icon-time::before {
  color: #bababa;
}

/deep/.el-icon-odometer::before {
  color: #fbcb6e;
}

/deep/.el-icon-circle-check::before {
  color: #22bb5f;
}

/deep/.el-icon-circle-close::before {
  color: #ff5555;
}

/deep/.el-calendar-day {
  position: relative;
  padding-top: 14px;
  .calendar-item-date {
    color: #ccc;
    position: absolute;
    right: 5px;
    top: 0px;
  }

  .check-more {
    position: absolute;
    width: calc(100% - 16px);
    font-size: 12px;
    bottom: 8px;
    border-radius: 4px;
    background-color: #efefef;
  }
}

/deep/.calendar-item-content {
  display: flex;
  flex-direction: column;
  margin: 4px 0;
}

/deep/.calendar-wrapper {
  margin-top: 10px;
}
/deep/.el-calendar__header {
  padding: 12px 0;
}
/deep/.el-calendar__body {
  padding-left: 0;
  padding-right: 0;
}
/deep/.el-calendar__title {
  font-size: 20px;
}
/deep/.el-calendar-table:not(.is-range) td.next,
/deep/.el-calendar-table:not(.is-range) td.prev {
  pointer-events: none;
}
/deep/.el-calendar-day {
  height: 120px;
}
/deep/.el-drawer__body {
  padding: 0 10px 10px 20px;
}

/deep/.el-step {
  flex-shrink: 0 !important;

  .el-step__main {
    cursor: pointer;
  }
}

/deep/.kr-list-table-box {
  min-width: 200px;
}

/deep/.list-table-search--item {
  margin: 0;
}

/deep/.search--btnOverflow {
  margin-bottom: 0;
}
</style>
